package com.sojson.result.interfaces.impl.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.sojson.config.exception.TransErrorCode;
import com.sojson.result.Result;
import com.sojson.result.interfaces.FilterResponseDataInterface;
import com.sojson.util.StringUtil;
import com.sojson.util.filter.FilterUtil;
import com.sojson.util.servlet.ServletUtil;

/**
 * 过滤器返回数据信息工具类接口(输出数据加页面跳转)
 * 
 * @author liu
 * @date 2020-11-02
 */
public class FilterResponseDataByOutOrRedirect implements FilterResponseDataInterface {

    private static FilterResponseDataByOutOrRedirect filterResponseDataByOutOrRedirect;

    private FilterResponseDataByOutOrRedirect() {}

    /**
     * 过滤器返回数据加重定向到指定页面
     * 
     * @throws IOException
     */
    @Override
    public void responseDate(ServletRequest request, ServletResponse response, TransErrorCode code, String url)
        throws IOException {
        // 判断是不是Ajax请求
        if (isAjax(request)) {
            out(response, Result.fail(code));
        } else {
            // 如果不是Ajax请求就跳转到提示页面
            redirect(request, response, url);
        }
    }

    /**
     * 判断一个对象是否是空(空对象)
     * 
     * @param obj
     * @return
     */
    private static boolean isBlankObject(Object obj) {
        return StringUtil.isBlankObject(obj);
    }

    /**
     * 是否是Ajax请求
     * 
     * @param request
     * @return
     */
    private boolean isAjax(ServletRequest request) {
        return FilterUtil.isAjax(request);
    }

    /**
     * 向页面打印数据
     * 
     * @param response
     * @param rspData 要打印的数据
     * @throws IOException
     */
    private void out(ServletResponse response, Object rspData) throws IOException {
        ServletUtil.out(response, rspData);
    }

    /**
     * 重定向到指定页面
     * 
     * @param request
     * @param response
     * @throws IOException
     */
    private void redirect(ServletRequest request, ServletResponse response, String url) throws IOException {
        FilterUtil.redirect(request, response, url);
    }

    public static FilterResponseDataByOutOrRedirect getInstances() {
        if (isBlankObject(filterResponseDataByOutOrRedirect)) {
            filterResponseDataByOutOrRedirect = new FilterResponseDataByOutOrRedirect();
        }
        return filterResponseDataByOutOrRedirect;
    }

}